package com.shark.teach;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther shark
 * @create 2024-08-06 13:51
 *
 * 100个线程，每个线程加100次，求最后的number值
 */
public class CASDemo
{

    // V1 多线程环境不使用原子类AtomicInteger保证线程安全（基本数据类型）
    private int number = 0;
    public int getNumber()
    {
        return number;
    }
    public synchronized void setNumber()
    {
        number++;
    }

    //V2 多线程环境    使用原子类AtomicInteger保证线程安全（基本数据类型）
    AtomicInteger atomicInteger = new AtomicInteger(0);

    public AtomicInteger getAtomicInteger()
    {
        return atomicInteger;
    }

    public void setAtomicInteger()
    {
        atomicInteger.incrementAndGet();

        atomicInteger.getAndIncrement();//讲解源码用
    }

    public static void main(String[] args) throws InterruptedException
    {
        CASDemo resource = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 1; i <=100; i++) {
            new Thread(() -> {
                for (int j = 1; j <=100 ; j++) {
                    resource.setNumber();
                    resource.setAtomicInteger();
                }
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }

        //try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        countDownLatch.await();

        System.out.println(Thread.currentThread().getName()+"\t"+"----result: "+resource.getNumber());
        System.out.println(Thread.currentThread().getName()+"\t"+"----resultV2: "+resource.getAtomicInteger().get());


    }

    private static void helloCAS()
    {
        AtomicInteger atomicInteger = new AtomicInteger(5);

        System.out.println(atomicInteger.compareAndSet(5, 620)+"\t"+atomicInteger.get());

        System.out.println(atomicInteger.compareAndSet(5, 999)+"\t"+atomicInteger.get());
    }
}
